﻿using System;
using System.Collections.Generic;
using System.Linq;
using Kugar.Core.ExtMethod;
using Kugar.Web.Wechat.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using JsonReader = Newtonsoft.Json.JsonReader;
using JsonWriter = Newtonsoft.Json.JsonWriter;

namespace Kugar.Web.Wechat.Serializers
{
    public class WeixinMenuNewtonsoftJsonSerializer :JsonConverter
    {
        private static HashSet<Type> _checkTypes=new HashSet<Type>()
        {
            typeof(WeixinMenuConfigItem),
            typeof(WeixinMenuRoot)
        };

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var tmp = (WeixinMenuConfigItem) value;

            writer.WriteStartObject();
            writer.WriteProperty("Title", tmp.Title);
            
            if ((value as WeixinMenuRoot)?.ChildMenus.HasData()==true)
            {
                var root = (WeixinMenuRoot)value;

                writer.WriteStartArray();
                
                foreach (var childMenu in root.ChildMenus)
                {
                    writer.WriteStartObject();
                    writer.WriteProperty("Title", childMenu.Title);
                    writer.WriteProperty("Value", tmp.Value);
                    writer.WriteProperty("Type", (int)tmp.Type);
                    writer.WriteEndObject();
                }

                writer.WriteEndArray();
            }
            else
            {

                writer.WriteProperty("Value", tmp.Value);
                writer.WriteProperty("Type", (int)tmp.Type);
            }
            
            writer.WriteEndObject();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var json = JObject.Load(reader);

            var childMenus = json.GetJObjectArray("ChildMenus");
            
            if (childMenus.HasData())
            {
                var tmp = new WeixinMenuRoot();

                tmp.Title = json.GetString("Title");

                tmp.ChildMenus=childMenus.Select(x => new WeixinMenuConfigItem()
                {
                    Title = x.GetString("Title"),
                    Type = (WeiXinMenuItemTypeEnum) x.GetInt("Type"),
                    Value = x.GetString("Value")
                }).ToArray();

                return tmp;
            }
            else
            {
                var tmp = new WeixinMenuConfigItem();

                tmp.Title = json.GetString("Title");
                tmp.Type = (WeiXinMenuItemTypeEnum)json.GetInt("Type");
                tmp.Value = json.GetString("Value");

                return tmp;
            }
        }

        public override bool CanConvert(Type objectType)
        {
            return _checkTypes.Contains(objectType);
        }
    }

}
